const routers = {
	// 主包
	'index': 'pages/index/main',
	'mine': 'pages/mine/main',
	'balance': 'pages/balance/main',
	'mineScan': 'pages/mineScan/main',
	'bindOldMember': 'pages/bindOldMember/main',
	'indexChooseCard': 'pages/indexChooseCard/main',
	'inviteRegister': 'pages/inviteRegister/main',
	'myCoupon': 'pages/myCoupon/main',
	'sendCard': 'pages/sendCard/main',
	'myIntegral': 'pages/myIntegral/main',
	'sendCardBuy': 'pages/sendCardBuy/main',
	'offlineReceiveCoupon': 'pages/offlineReceiveCoupon/main',
	'receiveCoupon': 'pages/receiveCoupon/main',
	'activeMineCard': 'pages/activeMineCard/main',
	'transfer': 'pages/transfer/main',
	'h5-login': 'pages/h5-login/index',
	'selectDiscount': 'pages/selectDiscount/main',


	// 寄存
	'deposit/': 'sp-deposit/',
	'deposit/myDeposit': 'pages/myDeposit/main',
	'deposit/reStore': 'pages/reStore/main',
	'deposit/depositDetail': 'pages/depositDetail/main',

	// 预订
	'booking/': 'sp-booking/',
	'booking/bookingIndex': 'pages/bookingIndex/main',
	'booking/shopList': 'pages/shopList/main',
	'booking/shopDetail': 'pages/shopDetail/main',
	'booking/submitBooking': 'pages/submitBooking/main',
	'booking/pickerCity': 'pages/pickerCity/main',
	'booking/orderDetailBillDetail': 'pages/orderDetailBillDetail/main',
	'booking/orderDetail': 'pages/orderDetail/main',
	'booking/calenderPicker': 'pages/calenderPicker/main',
	'booking/roomDetail': 'pages/roomDetail/main',

	// 会员
	'member/': 'sp-member/',
	'member/gklIndex': 'pages/gklIndex/main',
	'member/gklPaySuccess': 'pages/gklPaySuccess/main',
	'member/activeMemberCard': 'pages/activeMemberCard/main',
	'member/personInformation': 'pages/personInformation/main',
	'member/balanceDetail': 'pages/balanceDetail/main',
	'member/balanceRecharge': 'pages/balanceRecharge/main',
	'member/resetPassword': 'pages/resetPassword/main',
	'member/personSetting': 'pages/personSetting/main',
	'member/myInviteRecord': 'pages/myInviteRecord/main',
	'member/bindOldMemberConfirm': 'pages/bindOldMemberConfirm/main',
	'member/couponDetail': 'pages/couponDetail/main',
	'member/couponDetailNew': 'pages/couponDetailNew/main',
	'member/myOrderList': 'pages/myOrderList/main',
	'member/redemptionRecord': 'pages/redemptionRecord/main',
	'member/redemptionRecordDetails': 'pages/redemptionRecordDetails/main',
	'member/redemptionDetails': 'pages/redemptionDetails/main',
	'member/customerForm': 'pages/customerForm/main',
	'member/integralRule': 'pages/integralRule/main',
	'member/integralDetail': 'pages/integralDetail/main',
	'member/integralListDetail': 'pages/integralListDetail/main',
	'member/balanceListDetail': 'pages/balanceListDetail/main',
	'member/invalidCoupon': 'pages/invalidCoupon/main',
	'member/sendGiftDetail': 'pages/sendGiftDetail/main',
	'member/memberCardDetail': 'pages/memberCardDetail/main',
	'member/memberRenewal': 'pages/memberRenewal/main',
	'member/consumeActivityDetail': 'pages/consumeActivityDetail/main',
	'member/exchangeCoupon': 'pages/exchangeCoupon/main',
	'member/couponCenter': "pages/couponCenter/main",
	'member/consumeActivityDetailNew': "pages/consumeActivityDetailNew/main",
	'member/invalidCard': "pages/invalidCard/main",
	'member/cooperativeMerchant': "pages/cooperativeMerchant/main",

	// 点餐
	'catering/': 'sp-catering/',
	'catering/index': 'pages/index/main',
	'catering/shop': 'pages/shop/main',
	'catering/coupon': 'pages/coupon/main',
	'catering/city': 'pages/city/main',
	'catering/order': 'pages/order/main',
	'catering/remarks': 'pages/remarks/main',
	'catering/orderdetails': 'pages/orderdetails/main',
	'catering/gklIndex': 'pages/gklIndex/main',
	'catering/gklPaySuccess': 'pages/gklPaySuccess/main',


	//扫码点餐
	'codeorder/': 'code-order/',
	'codeorder/index': 'pages/index/main',
	'codeorder/shop': 'pages/shop/main',
	'codeorder/coupon': 'pages/coupon/main',
	'codeorder/city': 'pages/city/main',
	'codeorder/order': 'pages/order/main',
	'codeorder/remarks': 'pages/remarks/main',
	'codeorder/orderdetails': 'pages/orderdetails/main',
	'codeorder/gklIndex': 'pages/gklIndex/main',
	'codeorder/gklPaySuccess': 'pages/gklPaySuccess/main',
	'codeorder/myOrderList': 'pages/myOrderList/main',
	'catering/orderDetail': "pages/orderDetail/main",
	'codeorder/productDetail': "pages/proDetail/main",

	// 商城
	'mall/': 'sp-mall/',
	'mall/address': "pages/address/index",
	'mall/address-form': "pages/address-form/index",
	'mall/address-list': "pages/address-list/index",
	'mall/goods-detail': "pages/goods-detail/index",
	'mall/spellGroupPer': "pages/order-detail/spellGroupPer/index",
	'mall/goods-list': "pages/goods-list/index",
	'mall/order-detail': "pages/order-detail/index",
	'mall/shop-cart': "pages/shop-cart/index",
	'mall/store-cart': "pages/store-cart/index",
	'mall/store-page': "pages/store-page/index",
	'mall/store-detail': "pages/store-detail/index",
	'mall/submit-order': "pages/submit-order/index",
	'mall/submit-order-virtual': "pages/submit-order-virtual/index",
	'mall/store-buy': "pages/store-buy/index",
	'mall/store-buy-search': "pages/store-buy/search",
	'mall/index': "pages/index/index",
	'mall/active-page': "pages/active-page/index",
	"mall/profile": "pages/profile/index",
	"mall/order-list": "pages/order-list/index",
	"mall/inside-url": "pages/insideUrl/index",
	"mall/search": "pages/search/index",
	"mall/store-search": "pages/store-search/index",
	"mall/service-stores": "pages/service-stores/index",
	"mall/join-group": "pages/join-group/index",
	"mall/store-list": "pages/store-list/index",

  // 贷动信息
  'loanmove/':'loan-move/',
  'loanmove/index':'pages/index/main',
  'loanmove/signData':'pages/signData/main',
  'loanmove/signQrcode':'pages/signQrcode/main',
  'loanmove/afficheList':'pages/afficheList/main',
  'loanmove/afficheDetail':'pages/afficheDetail/main',


  //预约模块,和预定模块不一样
  'reservation/': 'sp-reservation/',
  'reservation/home': "pages/home/main",
  'reservation/detail': "pages/detail/main",
  'reservation/resources_detail': "pages/resources_detail/main",
  'reservation/reservation_order_detail': "pages/reservation_order_detail/main",
  'reservation/project_detail': "pages/project_detail/main",
  'reservation/submit_reservation': "pages/submit_reservation/main",
  'reservation/choose_resources': "pages/choose_resources/main",
  'reservation/reservation_success': "pages/reservation_success/main",
  'reservation/shopList': "pages/shopList/main",
  'reservation/return_good_detail': "pages/return_good_detail/main",

}

const tabBars = [
	'pages/index/main',
	'pages/mineScan/main',
	'pages/mine/main'
]

const checkRenamePath = function(path) {
	if (!path) {
		return ''
	}
	if (path.startsWith("/")) {
		path = path.substring(1)
	}
	if (path.startsWith('pages/bookingProductModule/')) {
		path = path.replace("pages/bookingProductModule/", "sp-booking/")
	} else if (path.startsWith('pages/depositModule/')) {
		path = path.replace('pages/depositModule/', "sp-deposit/")
	} else if (path.startsWith('pages/orderingModule/')) {
		path = path.replace('pages/orderingModule/', "sp-catering/")
	} else if (path.startsWith('pages/memberCardModule/')) {
		path = path.replace('pages/memberCardModule/', "sp-member/")
	}else if (path.startsWith('pages/reservationModule/')) {
		path = path.replace('pages/reservationModule/', "sp-reservation/")
	} else if (path.startsWith('pages/shop-mall/')) {
		path = path.replace('pages/shop-mall/', "sp-mall/pages/")
	} else if (path.startsWith('pages/memberCardModule/pages/gklIndex/main')) {
		path = path.replace('pages/memberCardModule/', "sp-catering/")
	} else if (path.startsWith('pages/codeModul/pages/orderdetails/main')) {
		path = path.replace('pages/codeModul/', "code-order/")
	} else if (path.startsWith('pages/codeModul/pages/index/main')) {
		path = path.replace('pages/codeModul/', "code-order/")
	} else if (path.startsWith('pages/codeModul/pages/proDetail/main')) {
		path = path.replace('pages/codeModul/', "code-order/")
	} else if (path.startsWith('pages/loanMove/pages/index/main')) {
		path = path.replace('pages/loanMove/', "loan-move/")

	}
	return path;
}

const encodeParams = function(params) {
	const rv = []
	Object.keys(params).forEach((key) => {
		let value = params[key]
		if (typeof value === 'undefined') {
			value = ''
		}
		rv.push([key, encodeURIComponent(value)].join('='))
		// console.log(encodeURIComponent(value),decodeURIComponent(encodeURIComponent(value)))
		// debugger
	})
	return rv.join('&')
}

const getRouterPath = function(options) {
	let {
		name,
		path
	} = options;
	let routePath = ''
	if (name) {
		if (name.indexOf('/') !== -1) {
			if (!routers[name]) {
				console.error("无效地址", name, path);
			}
			let module = name.split('/')[0]
			routePath = routers[module + "/"] + routers[name]
		} else {
			routePath = routers[name]
		}
	} else {
		routePath = checkRenamePath(path)
	}

	return routePath;
}

const getParams = function(options) {
	const {
		params,
		json
	} = options;
	if (json) {
		return encodeParams({
			json: JSON.stringify(json)
		})
	} else if (params) {
		return encodeParams(params)
	}
	return ""
}

const push = (options) => {
  const { redirect, events, success, fail, complete, isTab } = options;
  let routePath = getRouterPath(options)
  let params = getParams(options)
  if (tabBars.indexOf(routePath) !== -1) {
    if(params  && isTab) {
      getApp().globalData.tabParams = params
    }
    wx.switchTab({ url: "/" + routePath, success, fail, complete })
    return;
  }


  if (params) {
    routePath = routePath + "?" + params;
  }

  if (redirect) {
    wx.redirectTo({ url: "/" + routePath, success: success, fail: fail, complete: complete })

  } else {
    wx.navigateTo({ url: "/" + routePath, events: events, success: success, fail: fail, complete: complete })

  }
}
const redirectTo = function (options) {
  options.redirect = true;
  push(options)
}

const routerBehavior = Behavior({
  methods: {
    navigateTo: function (e) {
      let name = e.currentTarget.dataset.name
      let path = e.currentTarget.dataset.path
      let params = e.currentTarget.dataset.params
      let json = e.currentTarget.dataset.json
      push({ name, path, params, json })
    },
    redirectTo: function (e) {
      let name = e.currentTarget.dataset.name
      let path = e.currentTarget.dataset.path
      let params = e.currentTarget.dataset.params
      let json = e.currentTarget.dataset.json
      let redirect = true;
      push({ name, path, params, json, redirect })
    },
    callPhone: function (e) {
      let phone = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
        phoneNumber: phone
      })
    },
    toStop: function (e) {
      return true;
    }
  }
})
// 路由名称和路径映射
let routerMap = {}
for (let name in routers) {
  if (name.endsWith("/")) {
    continue;
  }
  if (name.indexOf("/") !== -1) {
    let module = name.split('/')[0]
    routerMap[routers[module + "/"] + routers[name]] = name;
  } else {
    routerMap[routers[name]] = name;
  }
}

const back = function () {
  wx.navigateBack();
}

const getRouterName = function (path) {
  if (!path) {
    return '';
  }

  if (path.indexOf("?") !== -1) {
    path = path.split("?")[0]
  }
  let routePath = checkRenamePath(path)
  return routerMap[routePath];
}

const requireMemberPages = ['myIntegral', 'balance', 'member/personSetting', 'member/personInformation', 'member/memberCardDetail','loanmove/signData','loanmove/signQrcode']
export default {
  push,
  back,
  redirectTo,
  getRouterName,
  checkRenamePath,
  routers,
  routerMap,
  requireMemberPages,
  routerBehavior,
  tabBars
}
